package com.mkh.st.common.utils;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 导入校验结果
 *
 * @Author: pc
 * @CreateDate: 2021/8/5 13:36
 */
@Accessors(chain = true)
@Data
public class ImportResult<T> {

	/**
	 * 一级过滤合法数据
	 */
	private Map<Integer, T> firstValidData = new HashMap<>();

	/**
	 * 消息
	 */
	private StringBuilder message = null;

	/**
	 * 此行数据是否合法
	 */
	private boolean rowValid = true;

	/**
	 * 当前行
	 */
	private Integer rowIndex = 0;

	/**
	 * 错误消息数据
	 */
	private Map<Integer, String> messageMap = new HashMap<>();

	/**
	 * 获取一个实例对象
	 *
	 * @return
	 */
	public static <T> ImportResult<T> getImportResult() {
		return new ImportResult<T>();
	}

	/**
	 * 完成行校验
	 *
	 * @param t
	 */
	public void completeRowValid(T t) {
		if (rowValid) {
			firstValidData.put(rowIndex, t);
		} else {
			messageMap.put(rowIndex, message.toString());
		}
		message = null;
	}

	/**
     * 完成行校验
	 *
	 */
	public void completeRowValid() {
		String content = message.toString();
		if (StrUtil.isNotBlank(content)) {
			messageMap.put(rowIndex, content);
		}
		message = null;
	}

	/**
	 * 设置行
	 *
	 * @param rowIndex
	 */
	public ImportResult<T> appendRowIndex(int rowIndex) {
		this.rowIndex = rowIndex;
		message = new StringBuilder("第" + rowIndex + "行: ");
		rowValid = true;
		return this;
	}

	/**
	 * 校验数据与追填信息
	 *
	 * @param str
	 * @param msg
	 */
	public ImportResult<T> appendIfNull(String str, String msg) {
		if (StrUtil.isBlank(str)) {
			message.append(msg).append("、");
			rowValid = false;
		}
		return this;
	}

	/**
	 * 追填信息
	 *
	 * @param msg
	 */
	public ImportResult<T> append(String msg) {
		message.append(msg).append("、");
		rowValid = false;
		return this;
	}

	/**
	 * 获取信息
	 *
	 * @return
	 */
	public String getMessage() {
		StringBuilder rs = new StringBuilder();
		if (messageMap.size() <= 0) {
			return rs.toString();
		} else {
			Object[] keys = messageMap.keySet().toArray();
			Arrays.sort(keys);
			for (int i = 0; i < keys.length; i++) {
				rs.append(messageMap.get(keys[i])).append("\n");
			}
			return rs.toString();
		}
	}

}
